# encoding: utf-8
require "logstash/filters/base"
require "logstash/namespace"
require "logstash/environment"
class LogStash::Filters::Delta < LogStash::Filters::Base

  config_name("delta")
  milestone 1

  config :match_oper, :validate => ["delta","sum"], :default => 'delta'
  config :input_field, :validate => :string
  config :output_field, :validate => :string, :default => 'delta'
  config :keywords, :validate => :array, :required => false #required for match_oper=='include'
  
  public
  def register 
    @kv_dict = {} #hash where keeps the last event value with same watching keywords
  end # def register
  
  private
  def do_oper(oper, event, kv_dict, combined_key)
    if oper == 'delta'
      event[@output_field] = event[@input_field].to_f - kv_dict[combined_key].to_f
    end
  end
  
  public
  def filter(event)
    has_input_field = event.include?(@input_field)
    all_keywords_exists = true
    combined_key = ''
    @keywords.each do |kw|
        combined_key += event[kw.to_s].to_s
        if !event.include?(kw.to_s)
            all_keywords_exists = false
            break
        end
    end
    event['all_keywords_exists'] = all_keywords_exists
    event['has_input_field'] = has_input_field
    if has_input_field and all_keywords_exists
        event['debug_1'] = combined_key
        if @kv_dict.has_key?(combined_key)
            event['debugHasKey'] = true
            do_oper(match_oper, event, @kv_dict, combined_key)
        end
        
        @kv_dict[combined_key] = event[@input_field].to_f
        event['debug_2'] = @kv_dict.to_s
    end
     
#    if match_oper == 'regex' #regex match
#        @regex_pattern = Regexp.new(@pattern)
#        if event[@match_field] =~ @regex_pattern
#            matched = true
#            event['debug'] = 'matched'
#        end
#    end #end of regex match

#     event['matched'] = matched
#     if !@lastEvent.nil? and matched
#        event[@output_field] = 
#         (event[@input_field].to_f) - (@lastEvent[@input_field]).to_f  
#     else
#       event[@output_field] = 0     
#     end
#
#     # remember event for next time
#    #@lastEvent = event
#     if matched
#        @lastEvent = event
#     end
       
  end # def filter

end # class LogStash::Filters::SimpleDelta
